package com.hdc.mumuwei.micro_account_server.config;

import com.alibaba.fastjson.JSON;
import com.hdc.mumuwei.micro_account_server.utils.Result;
import com.hdc.mumuwei.micro_account_server.utils.TokenUtil;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Mumuwei
 * @Description
 * @create 2021/11/21 11:11
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (RequestMethod.OPTIONS.name().equals(request.getMethod())) {
            return true;
        }

        String uid = request.getHeader("uid");
        String token = request.getHeader("token");
//        System.err.println("<" + uid + ">");
//        System.err.println("preHandle:" + token);
        /**
         * 判断请求是否携带 uid 和 token
         */
        if (uid == null || token == null || token == "" || uid == "") {
            returnJson(response, JSON.toJSONString(new Result<>(Result.ERR_REQ_HEADER_CODE, Result.REQUEST_HEADER_ERR_MSG)));
//            System.err.println("身份鉴权失败,数据不足");
            return false;
        }
        /**
         * 判断 uid 和token 是否匹配
         */
        int flag = TokenUtil.verify(token);
        if(flag == 2){
            returnJson(response, JSON.toJSONString(new Result<>(Result.ERR_TOKEN_CODE, Result.TOKEN_ERR_MSG)));
//            System.err.println("验证失败，请重新登录");
            return false;
        } else if (flag == 1){
            returnJson(response, JSON.toJSONString(new Result<>(Result.ERR_TOKEN_CODE, Result.TOKEN_ERR_MSG)));
//            System.err.println("登陆过期，请重新登录");
            return false;
        }

        flag = TokenUtil.getUserId(token).equals(uid) ? 1 : 2;
        if(flag == 2){
            returnJson(response, JSON.toJSONString(new Result<>(Result.ERR_TOKEN_CODE, Result.REQUEST_HEADER_ERR_MSG)));
            return false;
        }

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        ServletOutputStream outputStream = response.getOutputStream();
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * 返回数据封装函数
     * @param response 响应
     * @param json 返回数据
     */
    private void returnJson(HttpServletResponse response, String json) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("json/html;charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}
